﻿using interop.UIAutomationCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MetroUIAutomation
{
    public class MetroUIA
    { 
        public IntPtr AppWindow { get; set; }
        public uint AppProcessId;
        public IUIAutomationElement AppUIElement;

        IUIAutomation _automation;
        ApplicationActivationManager appActiveManager;
        public void StartUp(string appUserModelId, string arguments)
        {
            _automation = new CUIAutomation();
            appActiveManager = new ApplicationActivationManager();
            appActiveManager.ActivateApplication(appUserModelId, arguments, ActivateOptions.None, out AppProcessId);
            AppWindow = Win32.FindWindow("Windows.UI.Core.CoreWindow", "App1");
            AppUIElement = _automation.ElementFromHandle(AppWindow);
        }

        public void Close()
        {
            (AppUIElement.GetCurrentPattern(UIA_PatternIds.UIA_WindowPatternId) as IUIAutomationWindowPattern).Close();
        }

        public IUIAutomationElement GetElementByAutomationId(string automationId, IUIAutomationElement ancestor = null)
        {
            if (ancestor == null) ancestor = this.AppUIElement;
            IUIAutomationCondition conditionNote = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_AutomationIdPropertyId, automationId);
            return ancestor.FindFirst(TreeScope.TreeScope_Descendants, conditionNote);
        }

        public IUIAutomationElement GetElementByName(string name, IUIAutomationElement ancestor = null)
        {
            if (ancestor == null) ancestor = this.AppUIElement;
            IUIAutomationCondition conditionNote = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_NamePropertyId, name);
            return ancestor.FindFirst(TreeScope.TreeScope_Descendants, conditionNote);
        }

        public IUIAutomationElement ElementFromPoint(tagPOINT p)
        {
            return _automation.ElementFromPoint(p);
        }

        public IUIAutomationElement GetFocusedElement()
        {
            return _automation.GetFocusedElement();
        }

        public void Invoke(IUIAutomationElement sender)
        {
            IUIAutomationInvokePattern p = (IUIAutomationInvokePattern)sender.GetCurrentPattern(UIA_PatternIds.UIA_InvokePatternId);
            if (p != null)
            {
                p.Invoke();
            }
        }

        public string GetElementText(IUIAutomationElement textElement)
        {
            IUIAutomationTextPattern p = (IUIAutomationTextPattern)textElement.GetCurrentPattern(UIA_PatternIds.UIA_TextPatternId);
            if (p != null)
            {
                return p.DocumentRange.GetText(-1);
            }
            else
            {
                return textElement.CurrentName;
            }
        }
    }
}
